package lib

import (
	"github.com/segmentio/ksuid"
	"github.com/sony/sonyflake"
	"math/rand"
	"sync"
	"time"
)

var sf *sonyflake.Sonyflake

var rg = struct {
	sync.Mutex
	rand *rand.Rand
}{
	rand: rand.New(rand.NewSource(time.Now().UnixNano())),
}

func init() {
	f := sonyflake.Settings{
		StartTime: time.Now(),
	}

	sf = sonyflake.NewSonyflake(f)
	if sf == nil {
		panic("id generator init error")
	}
}

func int63nRange(min, max int64) int64 {
	rg.Lock()
	defer rg.Unlock()
	return rg.rand.Int63n(max-min) + min
}

func NextID() uint64 {
	id, err := sf.NextID()
	if err != nil {
		return uint64(int63nRange(1926425572, 1926425572223607))
	}

	return id
}

func NewKsuid() string {
	return ksuid.New().String()
}
